<?php
namespace Home\Controller;

use Think\Controller;
use Home\Event\WeixinEvent;
use Home\Controller\LetterController;

class NewUserCouponController extends BaseController {



    public function __construct(){
        parent::__construct();
        $this->member_id = $this->member_data['member_id'];
        if(!$this->member_id){
            $login = new LetterController();
            $status = $login->verify(1);
            if($status === false) {
                $this->redirect('Login/index', array('controller' => 'NewUserCoupon', 'action' => 'index', 'local_id' => I('get.local_id')));
            }
        }
    }

    public function index(){
        $this->display("NewUser/newUserCoupon");
    }
    public function indexAPI(){

        $page = max(I('get.page'), 1);
        $num = max(I('get.num'), 6);

        //满足规则 的领券包  开启，未过期
        $time = date('Y-m-d H:i:s',time());
        //$res =M('b2c_giftcode')->where(['status'=>'1','last_time'=>['gt',$time],'first_time'=>['lt',$time],'local_id'=>I('get.local_id',1)])->select();
        $res =M('b2c_giftcode')->where(['status'=>'1','local_id'=>I('get.local_id',1)])->select();

        if(empty($res)){
            $re_data['data'] = null;
        }else{
            //判断该用户是否已经领取
            foreach ($res as $k=>$v){
               //判断是否已经结束，或者未开始
               if($v['last_time'] < $time){
                   $res[$k]['dead'] = 1; //已经结束
               }elseif($v['first_time'] > $time){
                   $res[$k]['start'] = 1; //未开始
               }


               $is_get =  M('b2c_giftcode_member')->where(['member_id'=>$this->member_id,'giftcode_id'=>$v['id']])->find();
               if(!empty($is_get)){
                   $res[$k]['get'] = 1; //已经领取
               }else{
                   $res[$k]['get'] = 0; //未领取
               }


                if($v['type'] == 1){

                    $isBuy = M('b2c_orders')->where(['member_id'=>$this->member_id,'local_id'=>$v['local_id'],'pay_status'=>'1'])->find();
                    if(!empty($isBuy)){
                        $res[$k]['isNew'] = 0; //老用户
                    }else{
                        $res[$k]['isNew'] = 1; //是新用户
                    }

                }


               $res[$k]['enough'] = $this->isCouponEnough($v['gifg'],$v['local_id']);

            }

            $start=($page-1)*$num;
            $re_data['data'] = array_slice($res,$start,$num);
        }
        if(empty($re_data['data'])){
            $re_data['data'] = null;
        }
        $this->ajaxReturn($re_data);

    }
    //优惠券礼包详细
    public function isCouponBagDetail(){

        $bag_id = I('post.id',0);
        if($bag_id == 0){
            $this->ajaxReturn(['msg'=>'数据异常','status'=>0]);
        }

        $res =M('b2c_giftcode')->where(['id'=>$bag_id])->find();
        if(empty($res)){
            $re_data['data'] = null;
        }else{
            $coupon__rule_id = explode(',',$res['gifg']);
            foreach ($coupon__rule_id as $k=>$cv){
                $coupon_name =M('b2c_discount_coupon')->where(['id'=>$cv])->find()['name'];
                $re_data['data'][$k] = $coupon_name;
            }
        }
        $this->ajaxReturn($re_data);
    }

    //判断优惠券是否足够
    public function isCouponEnough($str='',$local_id){
        $isEnough = 1;
        if(!empty($str)){
            $coupon_id = explode(',',$str);
            foreach ($coupon_id as $k=>$value){
             $isFind = M('b2c_discount_coupon_code')->where(['discount_coupon_id'=>$value,'local_id'=>$local_id,'status'=>'0','member_id'=>0])->find();
                if(empty($isFind)){
                    $isEnough = 0;
                    break;
                }
            }

        }

        return $isEnough;
    }
    //领取礼券包
    public function getCouponBag(){
       $bag_id = I('post.id',0);
       if($bag_id == 0 ){
           $status_coupon['status'] = 4;
           $status_coupon['msg'] = '异常！';
           $this->ajaxReturn($status_coupon);
       }
       //开启事务
       $Mod = M();
       $Mod->startTrans();

       $time = date('Y-m-d H:i:s',time());
       $res = M('b2c_giftcode')->where(['id'=>$bag_id,'last_time'=>['gt',$time],'first_time'=>['lt',$time],'status'=>'1'])->find();

       if(!empty($res)){
          $zg = $this->isCouponEnough($res['gifg'],$res['local_id']);
          if($zg == 0){
              $status_coupon['status'] = 0; //已经被领光
              $status_coupon['msg'] = '已经被领光！';
              $this->ajaxReturn($status_coupon);
          }

          //领取优惠券礼包
           if(!empty($res['gifg'])){
               $coupon_id_list =  explode(',',$res['gifg']);
               $gift =array();
               foreach ($coupon_id_list as $k=>$item){
                   //选择一张优惠卷
                   $cou =  M('b2c_discount_coupon_code cc')
                       ->join("left join ".C('DB_PREFIX')."b2c_discount_coupon dc on cc.discount_coupon_id = dc.id and cc.local_id = dc.local_id ")
                       ->where(['cc.local_id'=>$res['local_id'],'cc.discount_coupon_id'=>$item,'cc.member_id'=>0,'cc.status'=>'0'])
                       ->order('dc.sort asc')
                       ->field('cc.id')
                       ->find();
                   //echo M()->getlastSql();

                   $gift[$k] = $cou['id'];

                   //如果赠送的优惠价已经送完
                   if(empty($cou['id'])){
                       unset($gift[$k]);
                       $status_coupon['status'] = 0; //已经被领光
                       $status_coupon['msg'] = '已经被领光！';
                       $this->ajaxReturn($status_coupon);
                   }
               }

               //纷发给会员
               foreach ($gift as $kk=>$vv){
                   $sendCoupon = M('b2c_discount_coupon_code')->where(['id'=>$vv,'status'=>'0','member_id'=>0])->save(['member_id'=>$this->member_id]);
                   if($sendCoupon === false){
                       $status_coupon['status'] = 2; //网络异常请稍候尝试
                       $status_coupon['msg'] = '网络异常请稍候尝试！';
                       $this->ajaxReturn($status_coupon);
                   }
               }
               //领取记录
               $giftcod_log = M('b2c_giftcode_member')->add(['member_id'=>$this->member_id,'giftcode_id'=>$bag_id,'num'=>1,'create_time'=>time()]);


               if($sendCoupon !== false && $giftcod_log !== false){
                  $Mod->commit();
               }else{
                   // 事务回滚
                   $Mod->rollback();
                   $this->ajaxReturn(array('msg'=>'网络异常','status'=>2));
               }
               $status_coupon['status'] = 3; //领取成功！
               $status_coupon['msg'] = '领取成功,请在个人中心查看！';
               $this->ajaxReturn($status_coupon);
           }


       }else{
           $status_coupon['status'] = 1; //该礼券包已经下架过期！
           $status_coupon['msg'] = '该礼券包已经下架过期！';
           $this->ajaxReturn($status_coupon);
       }

    }

}